package com.yohann.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.yohann.servicebase.exception.GuliException;
import com.yohann.vod.service.VodService;
import com.yohann.vod.utils.AliyunVodSDKUtils;
import com.yohann.vod.utils.ConstantVod;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author Yohann
 * @since 2020/8/10
 */
@Service
public class VodServiceImpl implements VodService {
    @Override
    public String uploadVideo(MultipartFile file) {
        String id = null;
        try {
            String fileName = file.getOriginalFilename();
            String title = Objects.requireNonNull(fileName).substring(0,fileName.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();

            UploadStreamRequest request = new UploadStreamRequest(ConstantVod.ACCESS_KEY_ID,ConstantVod.ACCESS_KEY_SECRET,title,fileName,inputStream);

            UploadVideoImpl uploadVideo = new UploadVideoImpl();
            UploadStreamResponse response = uploadVideo.uploadStream(request);

            if (response.isSuccess()){
                id = response.getVideoId();
            }else {
                id = response.getVideoId();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return id;
    }

    @Override
    public void removeVideo(String id) {
        try{
                DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(ConstantVod.ACCESS_KEY_ID,ConstantVod.ACCESS_KEY_SECRET);
                DeleteVideoRequest request = new DeleteVideoRequest();
                request.setVideoIds(id);
                DeleteVideoResponse response = client.getAcsResponse(request);
           }
        catch (ClientException e){
                throw new GuliException(20001, "视频删除失败");
           }
    }

    @Override
    public void removeVideoList(List<String> videoIdList) {
        String ids = StringUtils.join(videoIdList.toArray(), ",");
        removeVideo(ids);
    }
}